<?php

namespace Model;

use Daiyong\Db as db;

class ArticleType extends Common {
    public $table = 'article_type';

    public function rule() {
        return array(
            'name|must' => array(
                array('string', '类型名称必须在2~10个字符之间', 2, 10),
                array('only', '类型名称与已有数据重复,请修改', $this->table),
            ),
            'fid|must' => array('idInTable', '父级未填写或输入错误', $this->table, [0]),
        );
    }
    public function find($param) {
        $data = toArray(db::find($this->table, $param));
        return $data;
    }
    public function findAll($param = [], $orderBy = 'order by id desc', $limit = 'limit 0,1000') {
        $param = $this->findClear($param);
        $list = db::findAll($this->table, $param, $orderBy . ' ' . $limit);
        //加入父级信息
        $list = $this->typeAddFatherInfo($list);
        foreach ($list as $k => $v) {
            $fatherName = array_column($v['father'], 'name');
            $list[$k]['names'] = implode('/', array_merge($fatherName, [$v['name']]));
        }
        return $list;
    }
    public function export($param = [], $orderBy = '') {
        $title =  ['id', '类型'];
        $filePath = $this->exportExcel($title, function ($limit) use ($param, $orderBy) {
            $list = $this->findAll($param, $orderBy, $limit);
            foreach ($list as $k => $v) {
                //行内容设置与$title一一对应
                $list[$k] = array($v['id'], $v['names']);
            }
            return $list;
        });
        return $filePath;
    }
    public function edit($data) {
        $verify = $this->verify($data, $this->rule());
        if ($verify !== true) {
            return $this->error($verify);
        }
        $data = $this->auto($data); //加入或去除一些自动生成的字段
        if ($data['id']) {
            return db::update($this->table, $data, ['id' => $data['id']]);
        } else {
            return db::insert($this->table, $data);
        }
    }
    public function delete($param) {
        if (!$param['id']) return $this->error('为避免错误请传入id删除');
        //相关联信息判断
        $data = db::find($this->table, $param);
        if ($data['id']) {
            //检查是否存在子类型
            if (db::find($this->table . '|id', ['fid' => $data['id']])) {
                return $this->error('该类型还有子级,请将子级删除后再删除该类型');
            }
            //检查类型下是否存在内容
            if (db::find('article|id', ['tid' => $data['id']])) {
                return $this->error('该类型下还有内容,请先删除内容后再删除该类型');
            }
        }
        return db::delete($this->table, $param);
    }
    private function auto($data) {
        return $data;
    }
}
